//
//  ClipImageVC.m
//  Imagedemo
//
//  Created by 文杰 许                       on 2018/3/29.
//  Copyright © 2018年 文杰 许                      . All rights reserved.
//

#import "ClipImageVC.h"

@interface ClipImageVC ()
@property (nonatomic, strong) UIImage *oldImage;
@end

@implementation ClipImageVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.oldImage = self.imageView.image;
    
    self.imageView.image = nil;
    
    [self clipImage];
    
    [self clipImage2];
}

- (void)clipImage
{
    UIImage *image = self.oldImage;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    
    //开始绘制
    UIGraphicsBeginImageContext(image.size);
    CGContextRef con = UIGraphicsGetCurrentContext();
    
    CGContextMoveToPoint(con, width / 2, 0);
    CGContextAddLineToPoint(con, width, height/2);
    CGContextAddLineToPoint(con, width/2, height);
    CGContextAddLineToPoint(con, 0, height/2);
    CGContextClosePath(con);
    CGContextClip(con);
    //坐标系转换
    //因为CGContextDrawImage会使用Quartz内的以左下角为(0,0)的坐标系
    CGContextTranslateCTM(con, 0, height);
    CGContextScaleCTM(con, 1, -1);
    CGContextDrawImage(con, CGRectMake(0, 0, width, height), image.CGImage);
    
    //结束画图
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    self.imageView.image = newImg;
    
}

- (void)clipImage2
{
    UIImage *image = self.oldImage;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    
    //开始绘制
    UIGraphicsBeginImageContext(image.size);
    CGContextRef con = UIGraphicsGetCurrentContext();
    
    CGContextMoveToPoint(con, width / 2, 0);
    CGContextAddLineToPoint(con, width, height / 2);
    CGContextAddLineToPoint(con, width / 2, height);
    CGContextAddLineToPoint(con, 0, height / 2);
    CGContextClosePath(con);
    //加入矩形边框并调用CGContextEOClip函数
    CGContextAddRect(con, CGContextGetClipBoundingBox(con));
    CGContextEOClip(con);
    
    //坐标系转换
    //因为CGContextDrawImage会使用Quartz内的以左下角为(0,0)的坐标系
    CGContextTranslateCTM(con, 0, height);
    CGContextScaleCTM(con, 1, -1);
    CGContextDrawImage(con, CGRectMake(0, 0, width, height), image.CGImage);
    
    //结束绘制
    UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imageV = [[UIImageView alloc] initWithImage:newImg];
    imageV.frame = CGRectMake(100, 100, 300, 200);
    imageV.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 1.4);
    [self.view addSubview:imageV];
}

@end
